<!DOCTYPE html>
<html lang="en">
<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="威龙的博客">
    <meta name="keyword" content="随缘">
    <link rel="shortcut icon" href="/img/favicon.ico">

    <title>
        
        python日期及时间格式转换 - 威龙的博客 | VeyronC&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/aircloud.css">
    <link rel="stylesheet" href="/css/gitment.css">
    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_pl6z7sid89qkt9.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
</head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> 心若水， 自非凡。该博客已迁移至 https://www.cnblogs.com/xrszff </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar">
            <img src="/img/avatar.jpg">
        </div>
        <div class="name">
            <i>威龙</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li>
                <a href="/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li>
                <a href="/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li>
                <a href="/archive">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li>
                <a href="/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#字符串时间变成时间戳"><span class="toc-text">字符串时间变成时间戳</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#格林威治时间转数据库存储形式的时间"><span class="toc-text">格林威治时间转数据库存储形式的时间</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#datetime格式变时间戳"><span class="toc-text">datetime格式变时间戳</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#字符串转别的时间格式"><span class="toc-text">字符串转别的时间格式</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#时间格式转字符串"><span class="toc-text">时间格式转字符串</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#直接从字符串中提取月日"><span class="toc-text">直接从字符串中提取月日</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#得到今天昨天日期"><span class="toc-text">得到今天昨天日期</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#得到某月或某年"><span class="toc-text">得到某月或某年</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#得到上个月"><span class="toc-text">得到上个月</span></a></li></ol>
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input">
            <span id="begin-search">搜索</span>
        </div>
        <div style="padding:10px 20px;font=10;">
            若搜索无反应请更换浏览器~
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>
        <div class="index-about-mobile">
            <i> 心若水， 自非凡。该博客已迁移至 https://www.cnblogs.com/xrszff </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        python日期及时间格式转换
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2018-05-09 11:00:00</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/tags/#python" title="python">python</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>

    </div>
    <div class="post-content no-indent">
        <p>python脚本中经常会需要进行时间格式字符串和时间戳的转换，另外，也记一下datetime的用法。</p>
<p>用到time模块的地方都需要引入<code>import time</code></p>
<h1 id="字符串时间变成时间戳"><a href="#字符串时间变成时间戳" class="headerlink" title="字符串时间变成时间戳"></a>字符串时间变成时间戳</h1><figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">match_time = <span class="string">'2018-05-22 08:30:00'</span></span><br><span class="line">ans_time_stamp = time.mktime(time.strptime(match_time, <span class="string">"%Y-%m-%d %H:%M:%S"</span>))</span><br></pre></td></tr></table></figure>
<p>转换成的时间戳是float类型</p>
<h1 id="格林威治时间转数据库存储形式的时间"><a href="#格林威治时间转数据库存储形式的时间" class="headerlink" title="格林威治时间转数据库存储形式的时间"></a>格林威治时间转数据库存储形式的时间</h1><figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ltime = time.localtime(time.time())</span><br><span class="line">now_time = time.strftime(<span class="string">"%Y-%m-%d %H:%M:%S"</span>, ltime)</span><br></pre></td></tr></table></figure>
<h1 id="datetime格式变时间戳"><a href="#datetime格式变时间戳" class="headerlink" title="datetime格式变时间戳"></a>datetime格式变时间戳</h1><p>用pymysql从数据库取出来的时间，如果不为空（记得判断是否为空）则是 <code>datetime</code> 类型，可以直接相减得到 <code>datetime.timedelta</code> 类型，该类型想变时间戳用<code>total_seconds()</code>函数。<br><figure class="highlight lisp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">delta_time = check_time - ipo_time</span><br><span class="line">print(<span class="name">delta_time</span>.total_seconds())</span><br></pre></td></tr></table></figure></p>
<p>若是<code>datetime</code> 类型直接变时间戳用如下方法：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">import datetime</span><br><span class="line">import time</span><br><span class="line"></span><br><span class="line">dtime = datetime<span class="selector-class">.datetime</span><span class="selector-class">.now</span>()</span><br><span class="line"><span class="function"><span class="title">print</span><span class="params">(dtime)</span></span></span><br><span class="line">ans_time = <span class="selector-tag">time</span>.mktime(dtime.timetuple())</span><br><span class="line"><span class="function"><span class="title">print</span><span class="params">(ans_time)</span></span></span><br></pre></td></tr></table></figure></p>
<h1 id="字符串转别的时间格式"><a href="#字符串转别的时间格式" class="headerlink" title="字符串转别的时间格式"></a>字符串转别的时间格式</h1><figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Wed May 09 00:00:00 CST 2018 转 2018-05-09 00:00:00</span></span><br><span class="line">time_str = <span class="string">'Wed May 09 00:00:00 CST 2018'</span></span><br><span class="line">dt = datetime.datetime.strptime(time_str, <span class="string">"%a %b %d %X %Z %Y"</span>)</span><br></pre></td></tr></table></figure>
<h1 id="时间格式转字符串"><a href="#时间格式转字符串" class="headerlink" title="时间格式转字符串"></a>时间格式转字符串</h1><figure class="highlight cos"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># 日期转字符串</span><br><span class="line">local_str = dt.strftime('<span class="built_in">%Y</span>-<span class="built_in">%m</span>-<span class="built_in">%d</span> <span class="built_in">%H</span>:<span class="built_in">%M</span>:<span class="built_in">%S</span>')</span><br></pre></td></tr></table></figure>
<h1 id="直接从字符串中提取月日"><a href="#直接从字符串中提取月日" class="headerlink" title="直接从字符串中提取月日"></a>直接从字符串中提取月日</h1><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">import datetime</span><br><span class="line"><span class="selector-tag">a</span> = <span class="string">'2018-10-03 00:55:00'</span></span><br><span class="line"><span class="selector-tag">b</span> = datetime<span class="selector-class">.datetime</span><span class="selector-class">.strptime</span>(<span class="selector-tag">a</span>, <span class="string">'%Y-%m-%d %H:%M:%S'</span>).strftime(<span class="string">'%m-%d'</span>)</span><br></pre></td></tr></table></figure>
<h1 id="得到今天昨天日期"><a href="#得到今天昨天日期" class="headerlink" title="得到今天昨天日期"></a>得到今天昨天日期</h1><figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">today</span> = datetime.date.today() </span><br><span class="line"><span class="attr">yesterday</span> = today - datetime.timedelta(days=<span class="number">1</span>)</span><br><span class="line"><span class="comment"># 若要转成字符串还需要用str()</span></span><br></pre></td></tr></table></figure>
<h1 id="得到某月或某年"><a href="#得到某月或某年" class="headerlink" title="得到某月或某年"></a>得到某月或某年</h1><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">tmp_time = datetime.<span class="built_in">date</span>(<span class="number">2018</span>, <span class="number">7</span>, <span class="number">20</span>)</span><br><span class="line">tmp_time.<span class="built_in">month</span></span><br><span class="line">tmp_time.<span class="built_in">year</span></span><br></pre></td></tr></table></figure>
<h1 id="得到上个月"><a href="#得到上个月" class="headerlink" title="得到上个月"></a>得到上个月</h1><figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;</span>&gt; import datetime</span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; today = datetime.date.today()</span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; first = today.replace(day=<span class="number">1</span>)</span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; first</span><br><span class="line">datetime.date(<span class="number">2018</span>, <span class="number">10</span>, <span class="number">1</span>)</span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; last_month = first - datetime.timedelta(days=<span class="number">1</span>)</span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; print(last_month.strftime(<span class="string">"%Y%m"</span>))</span><br><span class="line"><span class="number">201809</span></span><br></pre></td></tr></table></figure>
<p>参考：</p>
<ul>
<li><a href="https://docs.python.org/3/library/datetime.html#module-datetime" target="_blank" rel="noopener">https://docs.python.org/3/library/datetime.html#module-datetime</a></li>
<li><a href="https://www.cnblogs.com/zknublx/p/6017094.html" target="_blank" rel="noopener">https://www.cnblogs.com/zknublx/p/6017094.html</a></li>
<li><a href="https://blog.csdn.net/u012422446/article/details/52639095" target="_blank" rel="noopener">https://blog.csdn.net/u012422446/article/details/52639095</a></li>
</ul>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src data-src="/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br>
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>

        <div id="lv-container">
        </div>

    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        
        <li>
            <a target="_blank" href="http://weibo.com/2983694150">
                            <span class="fa-stack fa-lg">
                                  <i class="iconfont icon-weibo"></i>
                            </span>
            </a>
        </li>
        

        

        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a href="https://www.10000h.top">10000H</a></span>
        <span>/</span>
        
        <span><a href="https://niexiaotao.com">Xiaotao&#39;s Page</a></span>
        <span>/</span>
        
        <span><a href="#">It helps SEO</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a href="https://hexo.io/">Hexo</a>  Theme <a href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="/js/index.js"></script>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>


    <script>
        /**
         *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
         *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
        */
        if( '' || '')
        var disqus_config = function () {
            this.page.url = '';  // Replace PAGE_URL with your page's canonical URL variable
            this.page.identifier = ''; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
        };

        (function() { // DON'T EDIT BELOW THIS LINE
            var d = document, s = d.createElement('script');
            s.src = 'https://airclouds-blog.disqus.com/embed.js';
            s.setAttribute('data-timestamp', +new Date());
            (d.head || d.body).appendChild(s);
        })();
    </script>



</html>
